<!--
 * @Author: pmy
 * @Date: 2021-09-02 14:39:12
 * @LastEditTime: 2022-11-25 09:57:21
 * @LastEditors: pmy
 * @Description: 查价记录表-table
 * @FilePath: \bdcar-net\src\components\table\baseTable.vue
-->
<template>
  <div class="tablePage" v-loading="loading">
    <div class="search">
      <div class="header-query" v-for="v in queryInput" :key="v.prop">
        <span class="search-text">{{ v.name }}</span>
        <el-input clearable v-model="v.value" :placeholder="v.placeholder" class="search-input"
          @change="pagination.currentPage = 1;"
          @keyup.native.enter="pagination.currentPage = 1; getTableData()"></el-input>
      </div>
      <div class="header-query" v-for="v in querySelect" :key="v.prop">
        <span class="search-text">{{ v.name }}</span>
        <el-select v-model="v.value" :placeholder="v.placeholder" filterable class="search-input"
          @change="pagination.currentPage = 1; getTableData()">
          <el-option v-for="vv in optionList[v.prop]" :key="vv.value" :label="vv.label" :value="vv.value"> </el-option>
        </el-select>
      </div>
      <div class="header-query" v-for="v in queryCascader" :key="v.prop">
        <span class="search-text">{{ v.name }}</span>
        <el-cascader v-model="v.value" class="search-input" :placeholder="v.placeholder" :options="optionList[v.prop]"
          :props="cascaderSet" @change="pagination.currentPage = 1; getTableData()" :clearable="false"></el-cascader>
      </div>
      <div class="header-query" v-for="v in queryTime" :key="v.prop">
        <span class="search-text">{{ v.name }}</span>
        <el-date-picker v-model="v.value" type="datetimerange" range-separator="至" :start-placeholder="v.placeholder[0]"
          :clearable="false" :end-placeholder="v.placeholder[1]" :picker-options="pickerOptions"
          class="search-input datedateTime-picker" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </div>

      <div class="search-btn" @click="getTableData()" v-if="Btn.search">
        <div class="btn-img"></div>查询
      </div>
    </div>


    <!-- #region 排序相关 -->
    <!-- <div class="base-table">
      <el-table highlight-current-row ref="myTable" :data="tableData" @selection-change="handleSelectionChange"
        height="100%" @sort-change="handleSortChange">

        <el-table-column :prop="v.prop" :label="v.name" v-for="v in tableItems" :key="v.prop" show-overflow-tooltip
        sortable="custom" :header-align="v.align ?? 'right'" :align="v.align ?? 'right'">
          <template slot-scope="scope">
            <span v-if="scope.row[v.prop] !== ''">{{ scope.row[v.prop] }}</span>
            <span v-else>---</span>
          </template>
</el-table-column>
</el-table>
</div> -->
    <div class="base-table">
      <el-table highlight-current-row ref="myTable" :data="tableData" @selection-change="handleSelectionChange"
        height="100%" @sort-change="handleSortChange">
        <!-- 指定列宽 -->
        <el-table-column :prop="v.prop" :label="v.name" v-for="v in tableItems" :key="v.prop" show-overflow-tooltip
          sortable="custom" :header-align="v.align ?? 'right'" :align="v.align ?? 'right'"
          :width="v.width ? v.width : '120px'">
          <template slot-scope="scope">
            <span v-if="scope.row[v.prop] !== ''">{{ scope.row[v.prop] }}</span>
            <span v-else>---</span>
          </template>
        </el-table-column>

      </el-table>
    </div>


    <div class="pagination">
      <el-pagination :page-size="pagination.pageSize" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="pagination.currentPage" :total="pagination.total"
        :page-sizes="[15, 50, 100, 300]" background layout="total,sizes, prev, pager, next, jumper"></el-pagination>
    </div>
  </div>
</template>
<script>
import treeSelect from "@/components/common/treeSelect"
import { service } from "../../services/backServices"
import FileControl from '@/components/common/FileControl.vue';
import { export_json_to_excel } from "@/assets/js/FilExport";
import dayjs from "dayjs";
export default {
  props: [
    "query",//查询参数
    "Btn",//自定义btn功能
    "menuName",//权限-菜单名称
    "pageName",//权限-页面名称
  ],
  components: { treeSelect, FileControl },
  data() {
    return {
      //#region 排序相关
      sortCol: "查询时间",
      // orderCol: "ascending",
      orderCol: "descending",
      //#endregion


      tableAllData: [],
      uploading: false,
      exportLoading: false,
      loading: false,
      method: {},
      //表格参数
      pagination: {
        total: 0,
        currentPage: 1,
        pageSize: 100,
      },
      multipleSelection: [],
      tableData: [],
      showWhich: "",
      updateInfo: {
        fileName: ''
      },
      params: {},
      cascaderSet: {
        value: 'value',
        emitPath: false,
        checkStrictly: false,
        expandTrigger: 'hover',
        multiple: false
      },
      addformRules: {
        fileName: [
          { required: true, message: '文件名称', trigger: 'blur' },
        ],
        fileAdd: [
          { required: true, message: '上传文件', trigger: 'blur' },
        ],
        uploadType: [
          { required: true, message: '上传类型', trigger: 'change' },
        ]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近两天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            },
          }
        ],
        disabledDate: (time) => {
          // return time.getTime() > Date.now() - 8.64e7;
          return time.getTime() > Date.now();
        },
      },
      showDialog: false,
      tableItems: [],
      methodParam: "getLogSearchPrice"
    };
  },
  computed: {
    queryInput() {
      let list = this.query.filter(v => {
        return v.type == "input"
      });
      return list;
    },
    querySelect() {
      let list = this.query.filter(v => {
        return v.type == "select"
      });
      return list;
    },
    queryCascader() {
      let list = this.query.filter(v => {
        return v.type == "cascader"
      });
      return list;
    },
    queryTime() {
      let list = this.query.filter(v => {
        return v.type == "time"
      });
      return list;
    },
    ImportAPI() {
      return GlobalSetting.IotConfig.ftpAPIService;
    },
  },
  created() {
    let _this = this;
    _this.method.addData = async function (model) {
      return service({
        headers: {
          'Content-Type': 'application/json'
        },
        method: 'post',
        url: _this.methodParam + "/save",
        data: model,
      });
    };
    _this.method.editData = async function editTrashOverflowData(model) {
      return service({
        headers: {
          'Content-Type': 'application/json'
        },
        method: 'post',
        url: _this.methodParam + "/update",
        data: model,
      });
    };
    _this.method.deleteData = async function (id) {
      let url = _this.methodParam + "/remove";
      return service({
        method: 'post',
        url: url,
        params: {
          id: id
        },
      });
    };
    _this.method.deleteDatas = async function (ids) {
      return service({
        method: 'post',
        url: _this.methodParam + "/batchRemove",
        params: {
          ids: ids
        },
        paramsSerializer: params => {
          return qs.stringify(params, {
            indices: false
          })
        }
      });
    };
    _this.method.uploadData = async function (data) {
      return service({
        headers: {
          'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryqs8javp5GsOgKvoQ'
        },
        method: 'post',
        url: _this.methodParam + "/upload",
        data: data,
        params: {
          uploadType: _this.updateInfo.uploadType
        }
      });
    };
    _this.method.downloadMethod = async function (url) {
      return service({
        method: 'post',
        url: _this.methodParam + "/download",
        responseType: 'blob',
        data: {
          url: url
        },
      });
    };
  },
  mounted() {
    this.getTableData();
  },
  methods: {

    getTableHead(query) {
      this.tableItems = [
        //{ name: "查询人姓名", prop: "查询人姓名"  },
        { name: "查询时间", prop: "查询时间", align: "left", width: "210px" },
        { name: "查询人姓名", prop: "查询人姓名", align: "left", width: "150px" },
        { name: "查询到手价", prop: "查询到手价", width: "150px" },
        { name: "产品条码与包数", prop: "产品代码与包数", width: "230px" },
        { name: "到手价", prop: "到手价" },
        { name: "总包数合计", prop: "总包数合计", width: "150px" },
        { name: "总大促底价合计", prop: "总大促底价合计", width: "190px" },
        { name: "总开单合计", prop: "总开单合计", width: "150px" },
        { name: "总日促底价合计", prop: "总日促底价合计", width: "190px" },
        { name: "总片数合计", prop: "总片数合计", width: "150px" },
        { name: "总赠品成本合计", prop: "总赠品成本合计", width: "190px" },
        { name: "折扣费率", prop: "折扣费率", width: "150px" },
        { name: "是否破大促价", prop: "是否破大促价", align: "left", width: "160px" },
        { name: "是否破日促价", prop: "是否破日促价", align: "left", width: "160px" },
      ]
    },
    setTableData() {
      this.tableData = this.tableAllData.slice(
        (this.pagination.currentPage - 1) * this.pagination.pageSize,
        this.pagination.currentPage * this.pagination.pageSize
      )

    },
    //表格参数改变触发
    handleSizeChange: function (val) {
      this.pagination.pageSize = val;
      this.setTableData();
    },
    handleCurrentChange: function (currentPage) {
      this.pagination.currentPage = currentPage;
      this.setTableData();
    },

    //#region 排序相关
    handleSortChange({ prop, order }) {
      this.sortCol = prop;
      this.orderCol = order;
      this.getTableData()
    },
    //#endregion

    getTableData() {
      let _this = this, query = {}
      this.loading = true
      this.query.forEach(v => {
        this.params[v.prop] = v.value
        query[v.prop] = v.value
      })
      let myForm = new FormData()
      myForm.append('startTime', query.searchTime[0])
      myForm.append('endTime', query.searchTime[1])
      myForm.append('searchUserName', query.searchUserName)

      //#region 排序相关（放在myForm之后）
      if (_this.sortCol != null) {
        myForm.append('sortBy', _this.sortCol)
      }
      if (_this.orderCol == 'ascending') {
        myForm.append('asc', 1)
      }
      //#endregion

      _this.getTableHead(query);
      let url = _this.methodParam;
      service({
        url: url,
        method: "post",
        data: myForm
      }).then(response => {
        this.loading = false
        if (response.data.code == 200) {
          this.tableAllData = response.data.data;
          this.setTableData();
          this.pagination.total = response.data.data.length;
          if (this.tableData.length == 0 && this.pagination.currentPage != 1) {
            this.pagination.currentPage = 1;
            this.getTableData();
          }
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = [];
      val.forEach(v => {
        this.multipleSelection.push(v.id);
      })
    },
    exportTable() {
      this.exportLoading = true;
      let _this = this;

      if (this.tableAllData.length <= 0) {
        _this.$notify({
          message: "当前数据为空",
          type: "error",
          position: "bottom-right",
          duration: 1000,
        });
        this.exportLoading = false;
        return;
      }
      let filename = "" + dayjs().format("YYYY-MM-DD HH:ss:mm");
      let multiHeader = []; //标题设置
      let tHeader = [], filterVal = [];

      _this.tableItems.forEach(v => {
        tHeader.push(v.name);
        filterVal.push(v.prop);
      })
      let jsonData = this.tableAllData;
      let merges = []; // 合并单元格
      export_json_to_excel({
        multiHeader,
        header: tHeader,
        merges,
        filterVal,
        jsonData,
        filename: filename,
        autoWidth: 30,
        bookType: "xlsx",
      });
      this.exportLoading = false;
    },
  },

  activated() {
    let _this = this;
    _this.$nextTick(() => {
      _this.$refs.myTable.doLayout();
    })
  }
}
</script>